//
//  HTTPTool.m
//  WuJieLive
//
//  Created by iMac on 2017/11/14.
//  Copyright © 2017年 zhk. All rights reserved.
//

#import "HTTPTool.h"
#import "AFNetworking.h"

@implementation HTTPTool

+ (AFHTTPSessionManager *)session {
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    session.requestSerializer.timeoutInterval = 10.0f;
    [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    session.responseSerializer.acceptableContentTypes = [session.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html"]];
    
    return session;
}

+ (NSURLSessionTask *)POSTForm:(NSString *)urlString
                          para:(id)para
                       success:(Success)success
                       failure:(Failure)failure

{
    AFHTTPSessionManager * session = [self session];
    
    NSLog(@"\n 请求地址: \n %@",urlString);
    
    NSLog(@"\n 请求参数为: \n %@",para);
    
    NSURLSessionTask * task = [session POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        if ([para isKindOfClass:[NSDictionary class]]) {
            NSArray * array = [para allKeys];
            for (int i = 0; i < array.count; i ++) {
                [formData appendPartWithFormData:[[para objectForKey:array[i]] dataUsingEncoding:NSUTF8StringEncoding] name:array[i]];
            }
        }else if(para == nil)
        {
            [formData appendPartWithFormData:[NSData new] name:@""];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"\n  返回结果 \n %@",responseObject);
        if (success) {
            if ([[responseObject objectForKey:@"code"] integerValue] == 0) { // 返回出去的数据是data 直接可用的
                success(YES,responseObject);
            }else if ([responseObject[@"code"] integerValue] == 5)  // token出错 重新登录
            {
                success(NO,responseObject);
                UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
                BaseNavigationController * navi = [[BaseNavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];
                self.isLogin = NO;
                self.nickName = @"";
                self.telephoneNumber = @"";
                self.password = @"";
                self.brithDay = @"";
                self.payForPassword = @"";
                self.redisKey = @"";
                self.userToken = @"";
                self.QRcodeUrl = @"";
                self.servicePhoneNum = @"";
                self.userImageString = @"";
                self.starPhoneNumber = @"";
                self.accountMoney = @"";
                [appRootVC presentViewController:navi animated:YES completion:nil];
            }
            else
            {    // 请求出错
                if ([[responseObject objectForKey:@"message"] isKindOfClass:[NSString class]]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if ([self presentedViewController]) {
                            [MBProgressHUD showError:[responseObject objectForKey:@"message"] toView:[self presentedViewController].view];
                        }else
                        {
                            [MBProgressHUD showError:[responseObject objectForKey:@"message"] toView:[self currentViewController].view];
                        }
                    });
                    //  下面这个判断是因为返回的错误信息字符太长 MBProgress没办法显示完全（或者是我没找到合适的解决方法） 就使用如下的方法返回出去错误信息 外面的block接受到返回的错误是字符串类型 就用alert提示错误
                    if ([[responseObject objectForKey:@"message"] length] > 20) {
                        success(NO,[responseObject objectForKey:@"message"]);
                    }else
                    {
                        success(NO,responseObject);
                    }
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
        NSLog(@"%@",error.localizedDescription);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self presentedViewController]) {
                [MBProgressHUD showError:@"请求服务器时发生错误" toView:[self presentedViewController].view];
            }else
            {
                [MBProgressHUD showError:@"请求服务器时发生错误" toView:[self currentViewController].view];
            }
        });
    }];
    
    [task resume];
    
    return task;
}

+ (void)uploadImageWithURL:(NSString *)URLString
                parameters:(id)parameters
               uploadImage:(NSData *)uploadImage
                   success:(Success)success
                   failure:(Failure)failure {
    
    AFHTTPSessionManager *session = [self session];
    NSURLSessionTask *task = [session POST:URLString
                                parameters:parameters
                 constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                     [formData appendPartWithFileData:uploadImage name:@"upload_file" fileName:@"aaa.jpg" mimeType:@"image/jpg"];
                 }
                                  progress:nil
                                   success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                       if (success) {
                                           if ([[responseObject objectForKey:@"code"] integerValue] == 0) {
                                               success(YES,responseObject);
                                           }else
                                           {
                                               success(NO,responseObject);
                                               if ([[responseObject objectForKey:@"message"] isKindOfClass:[NSString class]]) {
                                                   [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
                                               }else if ([[responseObject objectForKey:@"message"] isKindOfClass:[NSDictionary class]]){
                                                   NSArray * array = [[responseObject objectForKey:@"message"] allKeys];
                                                   NSArray * tempArray = [[responseObject objectForKey:@"message"] objectForKey:array[0]];
                                                   [MBProgressHUD showError:tempArray[0]];
                                               }
                                           }
                                       }
                                   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                       if (failure) {
                                           failure(error);
                                           [MBProgressHUD showError:error.description];
                                       }
                                   }];
    [task resume];
}

+ (UIViewController *)currentViewController {
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    } else {
        result = window.rootViewController;
    }
    
    return result;
}

+ (UIViewController *)presentedViewController {
    
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    if (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    
    return topVC;
}


+ (void)cancelAllOperations {
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.operationQueue cancelAllOperations];
}


@end
